import React, { useEffect, useState } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Space,
  Card,
  Divider,
  Typography,
  message,
  InputNumber,
  Popconfirm,
} from 'antd';
import {
  SearchOutlined,
  UndoOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  ClockCircleOutlined,
  AuditOutlined
} from '@ant-design/icons';
import RecordAllInfosPage from './modal';
import { useModel } from '@umijs/max';
import { pageRecord, programProgress, removeRecord } from '@/services/apis/companyRegister';
import dayjs from 'dayjs';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

// 状态选项（支持状态跳转机制）
const STATUS_OPTIONS = [
  { value: '待%审核', label: '待审核' },
  { value: '审核通过', label: '已通过' },
  { value: '审核不通过', label: '不通过' },
  { value: '审核退回', label: '已退回' },
];



// 新增：办理进度列表列配置（固定5个字段）
const progressColumns = [
  {
    title: (
      <Space align="center">
        {/* <ClockCircleOutlined /> */}
        <span>时间</span>
      </Space>
    ),
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 200,
    align: 'center',
  },
  {
    title: '单位',
    dataIndex: 'departmentName',
    key: 'departmentName',
    width: 200,
    align: 'center',
  },
  {
    title: '环节',
    dataIndex: 'link',
    key: 'link',
    width: 200,
    align: 'center',
  },
  {
    title: '结果',
    dataIndex: "resultStatus",
    key: 'resultStatus',
    width: 200,
    align: 'center',
  },
  {
    title: '意见',
    dataIndex: 'auditRemark',
    key: 'auditRemark',
    width: 200,
    render: (opinion: string) => (
      <Text >
        {opinion}
      </Text>
    ),
  },
];

const PilotEnterpriseRecordManagement: React.FC = () => {
  // 状态管理：新增进度相关状态
  const [recordList, setRecordList] = useState([]);
  const [searchForm] = Form.useForm(); // 搜索表单
  const [currentRecord, setCurrentRecord] = useState<any>(null); // 当前操作的备案记录
  const { initialState, setInitialState } = useModel('@@initialState');
  const [modalVisible, setModalVisible] = useState({
    edit: false, // 编辑弹窗
    review: false, // 审核弹窗
    progress: false, // 新增：进度弹窗控制
  });
  const [pageProps, setPageProps] = useState<{ current: number, pageSize: number, total: number }>({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const {
    modalProps,
    setModalProps,
  } = useModel("RecordManager.modal")
  const [currentProgressList, setCurrentProgressList] = useState<any[]>([]); // 新增：当前备案的进度数据

  // ---------------------- 新增：打开进度弹窗逻辑 ----------------------
  const handleProgressOpen = (record: any) => {
    programProgress({ companyId: record.companyId }).then(res => {
      const { code, data } = res
      if (code == "0") {
        setCurrentRecord(record);
        setCurrentProgressList(data);
      }
    })
    setModalVisible({
      ...modalVisible,
      progress: true
    });
  };

  // 1. 搜索功能：根据企业名称和状态筛选
  const handleSearch = async () => {
    const searchValues = await searchForm.validateFields();
    searchUsers({ ...searchValues, current: pageProps.current, size: pageProps.pageSize })
  };

  // 2. 重置搜索：恢复初始列表
  const handleReset = () => {
    searchUsers({ current: pageProps.current, size: pageProps.pageSize })
    searchForm.resetFields();
  };

  // 3. 删除备案记录：从列表中移除
  const handleDelete = (recordId: string) => {
    removeRecord({ id: recordId }).then(res => {
      const { code } = res
      if (code == "0") {
        //message.success("企业备案记录删除成功")
        searchUsers({ ...searchForm.getFieldsValue(), current: pageProps.current, size: pageProps.pageSize })
      }
    })
  };

  // 4. 打开编辑弹窗：加载当前备案的完整信息，新增关闭进度弹窗逻辑
  const handleEditOpen = (record: any, title: string) => {
    record.scenesData.forEach((item: any) => {
      record[item["label"]] = item.scenes
    })
    setModalProps(prev => ({ ...prev, visible: true, record, title }))
  };

  const searchUsers = (values: any) => {
    pageRecord({
      ...values,
      loginInArea: initialState?.currentUser.data.loginInArea,
      userType: initialState?.currentUser.data.userType,
    }).then(res => {
      const { code, data } = res
      if (code == "0") {
        const newRecord = data.records.map((item: any) => {
          return {
            ...item,
            productSolutionNames: item.digitalContentList?.reduce((pre: any, cur: { productName: any[]; }) => pre += cur.productName.join(","), ""),
            relatedServiceProviders: item.digitalContentList?.reduce((pre: any, cur: { connectService: any[]; }) => pre += cur.connectService.join(","), ""),
            digitalContentList: item.digitalContentList?.map((itemDigital: any) => ({
              ...itemDigital,
              programEnd: dayjs(itemDigital.programEnd),
              programStart: dayjs(itemDigital.programStart)
            }))
          }
        })
        setRecordList(newRecord)
        setPageProps({
          current: data.current,
          pageSize: data.size,
          total: data.total
        })
        //message.success("请求成功")
      }
    })
  }
  const usersPageOnchange = (current: any, pageSize: any) => {
    searchUsers({ ...searchForm.getFieldsValue(), current, size: pageSize })
  }
  useEffect(() => {
    searchUsers({ current: pageProps.current, size: pageProps.pageSize })
  }, [])
  // 表格列配置：新增“进度”按钮
  const tableColumns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: "10%",
      align: 'center',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '企业名称',
      dataIndex: 'companyName',
      key: 'companyName',
      ellipsis: true,
      width: "15%",
    },
    {
      title: '产品和解决方案名称',
      dataIndex: 'productSolutionNames',
      key: 'productSolutionNames',
      ellipsis: true,
      width: "15%",
      render: (text: string) => {
        if (!text) return '-';
        const items = text.split('、').filter(Boolean);
        return (
          <div>
            {items.map((item, index) => (
              <div key={index}>{item}</div>
            ))}
          </div>
        );
      },
    },
    {
      title: '关联服务商',
      dataIndex: 'relatedServiceProviders',
      key: 'relatedServiceProviders',
      ellipsis: true,
      width: "15%",
      render: (text: string) => {
        if (!text) return '-';
        const items = text.split('、').filter(Boolean);
        return (
          <div>
            {items.map((item, index) => (
              <div key={index}>{item}</div>
            ))}
          </div>
        );
      },
    },
    {
      title: '环节',
      dataIndex: 'link',
      key: 'link',
      width: "10%",
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'auditStatus',
      key: 'auditStatus',
      width: "10%",
      ellipsis: true,
      align: 'center',
    },
    {
      title: '操作',
      key: 'operation',
      width: "30%", // 加宽操作列容纳4个按钮
      align: 'center',
      render: (_: any, record: any) => (
        <Space size={2}>
          {/* 删除按钮 */}
          <Popconfirm title="是否删除" onConfirm={() => handleDelete(record.id)}>
            <Button
              type="primary"
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>

          {/* 编辑按钮 */}
          <Button
            size="small"
            type="primary"
            disabled={(() => {
              if (initialState?.currentUser.data.userType == "county") {
                return record.resultStatus != "待县（市、区）经商局审核"
              }
              if (initialState?.currentUser.data.userType == "city") {
                return record.resultStatus != "待市经信局审核"
              }
              return false
            })()}
            icon={<EditOutlined />}
            onClick={() => handleEditOpen(record, "编辑项目备案信息")}
          >
            编辑
          </Button>
          {/* 审核按钮：仅“待审核”状态可点击 */}
          <Button
            type="primary"
            size="small"
            disabled={(() => {
              if (initialState?.currentUser.data.userType == "county") {
                return record.resultStatus != "待县（市、区）经商局审核"
              }
              if (initialState?.currentUser.data.userType == "city") {
                return record.resultStatus != "待市经信局审核"
              }
              return false
            })()}
            onClick={() => handleEditOpen(record, "项目备案审核")}
            icon={<AuditOutlined />}
          >
            审核
          </Button>
          {/* 新增：进度按钮（所有状态可点击） */}
          <Button
            size="small"
            type="primary"
            icon={<ClockCircleOutlined />}
            // disabled={record.auditStatus == 'pending'}
            onClick={() => handleProgressOpen(record)}
          >
            进度
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '20px' }}>
      {/* 页面标题 */}
      <div
        style={{
          fontSize: 16,
          fontWeight: 500,
          color: '#1f2937',
          marginBottom: 12,
        }}
      >
        项目备案管理
      </div>

      {/* 第一部分：搜索栏 */}
      <Card style={{ marginBottom: '16px' }}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
        >
          <Form.Item
            name="enterpriseName"
            label="企业名称"
            rules={[{ whitespace: true, message: '请输入有效企业名称' }]}
          >
            <Input allowClear placeholder="请输入企业名称" style={{ width: '220px' }} />
          </Form.Item>
          <Form.Item name="auditStatus" label="状态">
            <Select placeholder="请选择状态" style={{ width: '180px' }} allowClear>
              {STATUS_OPTIONS.map((option) => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={handleReset} icon={<UndoOutlined />}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card
        style={{
          borderRadius: 12,
          boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
          // height: 'calc(100vh - 120px)', // 精确高度，保证内部滚动
          // overflowY: 'auto', // 内部滚动
          padding: '24px',
        }}
      >
        {/* 第二部分：企业备案列表 */}
        <Table
          columns={tableColumns as any}
          dataSource={recordList}
          rowKey="id"
          pagination={{
            pageSize: pageProps.pageSize,
            current: pageProps.current, total: pageProps.total, showSizeChanger: true,
            onChange: usersPageOnchange
          }}
          bordered
          scroll={{ y: 'calc(100vh - 450px)', x: "hidden" }}
          locale={{ emptyText: '暂无试点企业备案数据' }}
        />
      </Card>
      <RecordAllInfosPage searchCallFun={handleSearch} />
      {/* ---------------------- 新增：项目备案办理进度弹窗 ---------------------- */}
      <Modal
        title={`${currentRecord?.enterpriseName || '企业'}项目备案办理进度`}
        open={modalVisible.progress}
        onCancel={() => setModalVisible({ ...modalVisible, progress: false })}
        maskClosable={false}
        width={900}
        footer={[
          <Button key="close" onClick={() => setModalVisible({ ...modalVisible, progress: false })}>
            关闭
          </Button>
        ]}
        bodyStyle={{ maxHeight: '70vh', overflow: 'auto' }}
      >
        <Card bordered={false}>
          <Table
            columns={progressColumns as any}
            dataSource={currentProgressList}
            rowKey="id"
            pagination={false} // 进度列表完整展示，不分页
            bordered
            className="custom-table"

            locale={{ emptyText: '暂无该项目的备案办理进度记录' }}
            rowClassName={() => 'hover:bg-gray-50'} // 行悬浮高亮，提升交互体验
          />
        </Card>
      </Modal>
    </div>
  );
};

export default PilotEnterpriseRecordManagement;

